package com.wcgksoft.controller.order;


import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.admin.Account;
import com.wcgksoft.entity.goods.Goods;
import com.wcgksoft.entity.order.Order;
import com.wcgksoft.entity.order.OrderDetails;
import com.wcgksoft.entity.system.Enterprise;
import com.wcgksoft.entity.system.SysRole;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.SysRoleCodeService;
import com.wcgksoft.service.admin.AccountService;
import com.wcgksoft.service.goods.GoodsService;
import com.wcgksoft.service.order.OrderService;
import com.wcgksoft.service.system.EnterpriseService;
import com.wcgksoft.service.system.SysRoleService;
import com.wcgksoft.service.system.UserService;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 御风
 * @version V1.0
 * @Package com.wcgksoft.controller.goods
 * @Description 购物订单
 * @date 2020/5/12 16:11
 * @ClassName GoodsController
 */
@Controller
@RequestMapping("purchaseorder/list")
public class purchaseorderController {

  @Autowired
  private GoodsService goodsService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private UserService userService;

  @Autowired
  private AccountService accountService;
  @Autowired
  private EnterpriseService enterpriseService;
  @Autowired
  private SysRoleService sysRoleService;
  @Autowired
  private SysRoleCodeService sysRoleCodeService;
  @ResponseBody
  @RequestMapping(value = "findallorder")
  public Layui findallorder(@RequestParam(value = "page", required = false) Integer page,
                            @RequestParam(value = "limit", required = false) Integer limit,
                            @RequestParam(value = "status", required = false) Integer status) {
    Account account = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria criteria = DetachedCriteria.forClass(Order.class);
    if (null != status) {
      criteria.add(Restrictions.eq("status", status));
    }
    if (account.getAuthority().getRoleCode().equals("saleMan")) {
      criteria.add(Restrictions.eq("saleManId", account.getId()));
      criteria.add(Restrictions.eq("agentId", account.getAgent_id()));
    }else if(account.getAuthority().getRoleCode().equals("agent")){
      criteria.add(Restrictions.eq("agentId", account.getId()));
    }
    criteria.addOrder(org.hibernate.criterion.Order.desc("buyTime"));
    List<Order> list = orderService.findByConditions(criteria, page, limit);
    return Layui.data(0, "查询成功", goodsService.getTotalCount(), list);
  }

  @ResponseBody
  @RequestMapping(value = "find")
  public Layui findAll() {
    DetachedCriteria criteria = DetachedCriteria.forClass(Goods.class);
    List<Goods> list = goodsService.findByConditions(criteria);
    return Layui.data(0, "查询成功", list);
  }

  @ResponseBody
  @RequestMapping(value = "findgood")
  public Layui findgood(@RequestParam(value = "gid", required = false) Integer gid) {
    Goods goods = goodsService.findById(gid);
    return Layui.data(0, "查询成功", goods);
  }

  @ResponseBody
  @RequestMapping(value = "update")
  public Layui update(HttpServletRequest request,
                      @RequestParam(value = "data", required = false) String data,
                      @RequestParam(value = "goods", required = false) Integer[] goods,
                      @RequestParam(value = "numbers", required = false) Integer[] numbers) throws Exception {
    JSONObject param = JSONObject.fromObject(data);
    if (param == null) {
      return Layui.data(1, "请求格式有误", 0, null);
    } else {
      SysUser sysUser = null;
      Order order = (Order) JSONObject.toBean(JSONObject.fromObject(data), Order.class);
      order.setOrderNo(getOrderIdByTime());
      Account account = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");
      sysUser = (SysUser) JSONObject.toBean(JSONObject.fromObject(data), SysUser.class);
      if (account.getAuthority().getRoleCode().equals("saleMan")) {
        order.setAgentId(account.getAgent_id());
        order.setSaleManId(account.getId());
        sysUser.setAgent_id(account.getAgent_id());
        sysUser.setSaleMan_id(account.getId());
      }else if(account.getAuthority().getRoleCode().equals("agent")){
        order.setAgentId(account.getId());
        order.setSaleManId(account.getId());
        sysUser.setAgent_id(account.getId());
        sysUser.setSaleMan_id(account.getId());
      }
      order.setBuyTime(new Date());
      order.setStatus(1);
      order.setDeletetype(0);
      order.setAccountname(account.getName());

      sysUser.setStatus(1);
      sysUser.setIsView(1);
      sysUser.setIsCross(1);
      sysUser.setHealthScore("0");
      sysUser.setCreateDate(new Date());
//      SysUser user = new SysUser();

      /*企业绑定*/
      Enterprise enterprise = new Enterprise();
      enterprise.setDepartName(sysUser.getName());
      enterpriseService.save(enterprise);
      sysUser.setName(enterprise.getDepartName());
      sysUser.setEnterprise(enterprise);
      sysUser.setCompanyName(enterprise.getDepartName());
      sysUser.setStatus(1);
      SysRole role = new SysRole();
      role.setSysRoleCode(sysRoleCodeService.findById(2));
      role.setAdd_time(new Date());
      role.setEnterprise(enterprise);
//      role.setSysMenuSet(set);
      sysRoleService.save(role);
      sysUser.setSysRole(role);/*TODO 企业ID是二目前写死*/
      userService.save(sysUser);
      Integer number = account.getUserNumber();
      if (null == number) {
        account.setUserNumber(0);
      } else {
        account.setUserNumber(number + 1);
      }

      accountService.saveMerge(account);
      order.setSysUser(sysUser);

      HashSet<OrderDetails> details1 = new HashSet<>();
      for (int i = 0; i < goods.length; i++) {
        OrderDetails details = new OrderDetails();
        details.setGoods(goodsService.findById(goods[i]));
        details.setOrder(order);
        details.setNumbers(1);
        details.setNumbers(numbers[i]);
        details1.add(details);
      }

      order.setDetailsSet(details1);
      orderService.saveOrUpdate(order);
      return Layui.data(0, "保存成功", 1, Layui.addList(order));
    }
  }

  /**
   * 删除
   *
   * @param id
   * @param
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "delete")
  @Transactional
  public Layui delete(@RequestParam(value = "id") Integer id) {
    System.out.println("id" + id);
    Order byId = orderService.findById(id);
    byId.setDeletetype(1);
    orderService.saveMerge(byId);

    return Layui.data(1, "删除成功", 1, null);
  }

  public static String getOrderIdByTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String newDate = sdf.format(new Date());
    String result = "";
    Random random = new Random();
    for (int i = 0; i < 3; i++) {
      result += random.nextInt(10);
    }
    return newDate + result;
  }
}
